<template>
  <div>
    <el-dialog v-model="visible" :show-close="false">
      <template #header="{ close, titleId, titleClass }">
        <div class="my-header">
          <h4 :id="titleId" :class="titleClass">添加产品价格</h4>
        </div>
      </template>

      <div>
        <el-form :model="formData" label-width="120px" ref="elFormRef">
          <el-form-item label="价格名称">
            <el-input v-model="formData.money_name" style="width: 180px" />
          </el-form-item>

          <el-form-item label="商品价格">
            <el-input-number v-model="formData.money" :min="0"  />
          </el-form-item>

          <el-form-item label="折扣价格">
            <el-input-number v-model="formData.discount_money" :min="0" />
          </el-form-item>
        </el-form>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="close">关闭</el-button>

          <el-button type="primary" @click="handleSubmit">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang='ts' setup>
import { ref, onMounted } from 'vue'
import { GoodsPriceAddAndEdit } from '@/api/index'
import { ElMessage } from 'element-plus'

const visible = ref(false)

const elFormRef = ref(null)

const open = (config) => {
  Object.assign(formData.value, config.params.goodsPriceData)

  visible.value = true
}

const close = () => {
  visible.value = false
}

const formData = ref({
  id: '',
  goodsId: '',
  money_name: '',
  money: '',
  discount_money: '',
  method: 'add'
})

const resetFormData = () => {
  formData.value = {
    id: '',
    goodsId: '',
    money_name: '',
    money: '',
    discount_money: '',
    method: 'add'
  }
}

const handleSubmit = async () => {
  try {
    formData.value.method = formData.value.id ? 'edit' : 'add'

    const res = await GoodsPriceAddAndEdit(formData.value)

    ElMessage({
      message: `价格${formData.value.id ? '修改' : '添加'}成功!`,
      type: 'success'
    })

    resetFormData()

    emit('reload')

    close()
  } catch(err) {
    console.log('handleSubmit', err)

    ElMessage({
      message: '添加价格失败!',
      type: 'error'
    })
  }
}

// 暴露方法给父组件
defineExpose({
  open
});

const emit = defineEmits(['reload'])

onMounted(() => {
  // open()
})
</script>

<style lang='scss' scoped>

</style>
